<?php
use think\Db;
use app\common\model\ApplyLiveModel;
use app\common\model\CompanyModel;
use app\common\model\ChatRoomModel;
use app\common\model\ChatRoomLogModel;
use app\common\model\ChatMemberModel;
use app\common\model\ChatMemberLogModel;

/*
 * 参数一;  公司id
 * 参数二： 直播申请id (也是room_id)
 * 参数三： type 1是公司进入房间；0是公司离开房间
 * 参数四： client_id (连接id)
 * */

function company_chat_room($companyId,$live_id,$type,$client_id)
{
    $company  = CompanyModel::get($companyId);//直播公司的基本信息
    $apply    = ApplyLiveModel::get(['id' => $live_id]);

    $find = ChatRoomModel::get(['live_id' =>$live_id],'apply_live');

    if (time() <= $apply['start_time'] && $apply['is_open'] == 0) {
        // 从未创建过房间
        //开始事务
        Db::startTrans();
        try{
            if ($type == 0) {
                throw new \Exception('类型传入错误！'); // 未创建过房间 应该是 进入房间 类型操作
            }

            // 从未创建过房间
            $chat_room = new ChatRoomModel();
            $chat_room->data([
                'live_id'     => $live_id,
                'client_name' => $apply['theme'],
                'company_id'  => $companyId,
                'create_time' => time()
            ]);

            if (!$chat_room->save()) {
                throw new \Exception('网络错误，请稍后再试！');
            }

            $chat_room_log = new ChatRoomLogModel();
            $chat_room_log->data([
                'live_id'     => $live_id,
                'type'        => $type,      // 1是公司进入房间；0是公司离开房间
                'time'        => time(),     // 时间（当type=1就是进入时间当type=0就是离开时间）
                'create_time' => time()
            ]);

            if (!$chat_room_log->save()) {
                throw new \Exception('网络错误，请稍后再试！');
            }

            // 将公司加入人员名单
            $chat_member = new ChatMemberModel();
            $chat_member->data([
                'live_id'     => $live_id,
                'type'        => 2, // 1是用户；2是公司
                'member_id'   => $companyId,
                'create_time' => time()
            ]);

            if (!$chat_member->save()) {
                throw new \Exception('网络错误，请稍后再试！');
            }

            $chat_member_log = new ChatMemberLogModel();

            $chat_member_log->data([
                'status'         => 1, // 1是在线；2是下线
                'chat_member_id' => $chat_member->id,
                'client_id'      => $client_id,
                'create_time' => time()
            ]);

            if (!$chat_member_log->save()) {
                throw new \Exception('网络错误，请稍后再试！');
            }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $result = array('status' => false, 'msg' => $e->getMessage());
            return json($result);
        }
    }

    if (time() <= $apply['start_time'] && $apply['is_open'] == 3) {
        // 创建过房间 目前是离开状态

        // 创建过房间
        //开始事务
        Db::startTrans();
        try{
            // 新建公司 进出聊天室记录 chat_room_log
            $chat_room_log = new ChatRoomLogModel();
            $sqlData = [
                'live_id' => $live_id,   // 关联直播id
                'type'    => $type, // 1是公司进入房间；0是公司离开房间
                'time'    => time(),
                'create_time' => time()
            ];

            $logData = [];

            if ($type == 0) {
                // 0是公司离开房间  人员进出日志 chat_member_log
                $logData['status'] = 2; // 1是在线；2是下线
                $where = [
                    'live_id' => $live_id,
                    'type'    => 1,
                ];
                $new_log = ChatRoomLogModel::where($where)->order('id desc')->find();
                $whe = [
                    'live_id' => $live_id,
                    'type'    => 0,
                ];
                $end_log = ChatRoomLogModel::where($whe)->order('id desc')->find();
                if (!$end_log) {
                    $end_log['second'] = 0;
                }
                $sqlData['second'] = time() - $new_log['time'] + $end_log['second'];// 当前时间 减去 最新的进入的时间 等于 这次的进入聊天室的时间  再加上 之前离开房间记录下的历史进入总用时   就 等于  到现在为止的累计 进入聊天室用时
                Db::name('apply_live')->where('id',$live_id)->update(['second' => $sqlData['second']]);

                $find->is_online = 0;
                $find->save();

//                        if (!$find->save()) {
//                            throw new \Exception('网络错误，请稍后再试1！');
//                        }
            } else {
                $find->is_online = 1;
                $find->save();
//                        if (!$find->save()) {
//                            throw new \Exception('网络错误，请稍后再试2！');
//                        }

                $logData['status'] = 1; // 1是在线；2是下线
            }

            $chat_room_log->data($sqlData); // 插入 进出房间记录

            $chat_room_log->save();

//                    if (!$chat_room_log->save()) {
//                        throw new \Exception('网络错误，请稍后再试3！');
//                    }

            $chat_member = ChatMemberModel::get(['live_id' => $live_id,'type' => 2,'member_id' => $companyId]);

            $chat_member_log = new ChatMemberLogModel();
            $logData['chat_member_id'] = $chat_member['id'];
            $logData['client_id']      = $client_id;
            $logData['create_time']    = time();

            $chat_member_log->data($logData);
            if (!$chat_member_log->save()) {
                throw new \Exception('网络错误，请稍后再试4！');
            }

            // $logData['status'] = 1; // 1是在线；2是下线
            $chatMember = ChatMemberModel::get(['live_id' => $live_id,'type' => 2,'member_id' => $companyId]);

            if ($logData['status'] == 1) {
                $chatMember->is_online = 1;
            } else {
                $chatMember->is_online = 0;
            }

            $chatMember->save();

//                    if (!$chatMember->save()) {
//                        throw new \Exception('网络错误，请稍后再试5！');
//                    }

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $result = array('status' => false, 'msg' => $e->getMessage());
            return json($result);
        }

    }

    $result = array('status' => true, 'msg' => '商家进入聊天室 或者是 离开聊天室 记录 成功！');
    return true;
}


// 角色为 用户的 人进入聊天室 或者是离开聊天室

/*
 * 参数一;  用户id
 * 参数二： 直播申请id (也是room_id)
 * 参数三： type 1是用户进入房间；0是用户离开房间
 * 参数四： client_id (连接id)
 * */

function user_chat_room($userId,$live_id,$type,$client_id)
{
    $apply     = ApplyLiveModel::get($live_id);
    $roomModel = ChatRoomModel::get(['live_id' => $live_id]);
    if (!$roomModel) {
        $result = array('status' => false, 'msg' => '公司暂未进入直播间开始直播！');
        return json($result);
    }
    if ($roomModel['is_online'] == 0) {
        $result = array('status' => false, 'msg' => '公司已关闭此直播间！');
        return json($result);
    }

    if ($apply['is_open'] == 1) {
        $chat_member = ChatMemberModel::get(['live_id' => $live_id,'type' => 1,'member_id' => $userId]);
        if (!$chat_member) {
            // 用户从未进入此直播间
            //开始事务
            Db::startTrans();
            try{
                $member = new ChatMemberModel();
                $sqlData = [
                    'live_id'     => $live_id,
                    'type'        => 1,  // type 1是用户；2是公司
                    'member_id'   => $userId,
                    'create_time' => time()
                ];
                $finalData = [];
                // type 1是用户进入房间；0是用户离开房间
                if ($type == 1) {
                    $sqlData['is_online'] = 1;
                    $finalData['status']  = 1;
                } else {
                    $sqlData['is_online'] = 0;
                    $finalData['status']  = 2;
                }
                $member->data($sqlData); // 插入 这个直播间 的 人员列表  chat_member
                if (!$member->save()) {
                    throw new \Exception('网络错误，请稍后再试a！');
                }
                $finalData['chat_member_id'] = $member->id;
                $finalData['client_id']      = $client_id;
                $finalData['create_time']    = time();
                $chat_member_log = new ChatMemberLogModel();
                $chat_member_log->data($finalData); // 插入 人员 进出日志
                if (!$chat_member_log->save()) {
                    throw new \Exception('网络错误，请稍后再试b！');
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $result = array('status' => false, 'msg' => $e->getMessage());
                return json($result);
            }
        } else {
            // 用户进入过此直播间
            //开始事务
            Db::startTrans();
            try{
                $chat_member->is_online = $type;
                $chat_member->save();
                $insertData = [];
                if ($type == 1) {
                    $insertData['status'] = 1;
                } else {
                    $insertData['status'] = 2;
                }
                $insertData['chat_member_id'] = $chat_member->id;
                $insertData['client_id']      = $client_id;
                $insertData['create_time']    = time();
                $log = new ChatMemberLogModel();
                $log->data($insertData);
                if (!$log->save()) {
                    throw new \Exception('网络错误，请稍后再试！');
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $result = array('status' => false, 'msg' => $e->getMessage());
                return json($result);
            }
        }

        $result = array('status' => true, 'msg' => '客户端用户进入聊天室 或者是 离开聊天室 记录 成功！');
        return true;
    }

}